<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border style="width: 100%" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 角色下的权限渲染 -->
            <!-- 一级循环 -->
            <el-row v-for="item1 in scope.row.children" :key="item1.id" :class="['row_top', 'row_tag_center']">
              <el-col :span="5">
                <el-tag type="primary" closable @close="removeAuth(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级循环 -->
                <el-row v-for="(item2, index2) in item1.children" :key="item2.id" :class="['row_tag_center', index2 === 0 ? '' : 'col1_top']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeAuth(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级循环 -->
                    <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeAuth(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editeRole(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="clearDialog('roleForm')">
      <!-- 对话框主体内容(elementUI 的 这个对话框实则写好了循环) -->
      <el-form :model="roleForm" :rules="roleFormRules" ref="roleForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑" :visible.sync="editeDialogVisible" width="50%" @close="clearDialog('editeRoleForm')">
      <!-- 对话框主体内容(elementUI 的 这个对话框实则写好了循环) -->
      <el-form :model="roleForm" :rules="roleFormRules" ref="editeRoleForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editeRoleData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 展示权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="RightsDialog" width="50%" @close="setRightsDialogClose">
      <el-tree :data="rightsList" :props="rightsProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="checkedAuthId" ref="treeRightsRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commonAPI from '@/api/commonAPI/commonAPI.js'
// 导入混入模块
import { minxin, clearDialog } from '@/mixin.js'
export default {
  data() {
    return {
      // 权限列表(树形)
      rightsList: [],
      // 是否显示分配权限对话框
      RightsDialog: false,
      // el-tree组件的 props属性绑定的对象
      rightsProps: {
        children: 'children', // 父子嵌套的数据
        label: 'authName' // 展示给用户看的数据
      },
      // 默认选中的数组(内部是选中的权限id值)
      checkedAuthId: [],
      // 当前打开用户权限对话框的id值
      roleId: null,
      // 修改角色
      edite: {
        currentId: ''
      },
      // 角色列表
      rolesList: [],
      editeDialogVisible: false,
      dialogVisible: false,
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添角色的规则
      roleFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoles()
  },
  mixins: [minxin, clearDialog],
  methods: {
    // 添加用户角色
    addRole() {
      this.$refs.roleForm.validate(async valid => {
        // 单击确定时效验
        this.dialogVisible = false // 关闭添加角色对话框
        // 把角色添加数据库中
        const { data: res } = await commonAPI({ method: 'post', url: 'roles', params: this.roleForm })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 请求最新的数据,渲染模板
        this.getRoles()
      })
    },
    // 编辑用户角色
    async editeRole(id) {
      this.editeDialogVisible = true
      const { data: res } = await commonAPI({ method: 'get', url: `roles/${id}` })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(`请求用户角色id为${id}的用户数据失败!`)
      this.$message.success(`请求用户角色id为${id}的用户数据成功!`)
      this.edite.currentId = id
    },
    editeRoleData() {
      this.$refs.editeRoleForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await commonAPI({ method: 'put', url: `roles/${this.edite.currentId}`, params: this.roleForm })
        if (res.meta.status !== 200) return this.$message.error('编辑用户角色失败')
        this.$message.success('编辑用户角色成功')
        // 重新请求数据,获取最新的用户数据,渲染模板(id值后端帮生成)
        this.getRoles()
        // 关掉对话框
        this.editeDialogVisible = false
      })
    },
    // 删除单个用户角色
    async deleteRole(id) {
      const { data: res } = await commonAPI({ method: 'delete', url: `roles/${id}` })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 请求最新的数据,渲染模板
      this.getRoles()
    },
    // 移除权限
    async removeAuth(role, authId) {
      const resolve = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      const { data: res } = await commonAPI({ method: 'delete', url: `roles/${role.id}/rights/${authId}` })
      if (res.meta.status !== 200) return this.$message.info('删除权限失败!')
      if (resolve === 'confirm') this.$message({ type: 'success', message: res.meta.msg })
      // console.log(res)
      // 这样写,会渲染整个表格,体验不好
      // this.getRoles()
      // 这样只渲染权限
      role.children = res.data
    },
    // 展示权限对话框
    async showSetRightsDialog(role) {
      // 把打开用户权限对话框的 用户ID保存到data中,待用
      this.roleId = role.id
      const { data: res } = await commonAPI({ method: 'get', url: 'rights/tree' })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.getLeafKeys(role, this.checkedAuthId)
      this.RightsDialog = true
    },
    // 通过递归的形式,获取三级权限的id值,并保存到checkedAuthId中
    getLeafKeys(node, arr) {
      if (!node.children) {
        // 添加到arr数组中
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 当关闭对话框时,清空选中的权限
    setRightsDialogClose() {
      this.checkedAuthId = []
    },
    // 为角色分配权限
    async allotRights() {
      // 得到所有的半选和全选的id值
      const allkeys = [...this.$refs.treeRightsRef.getCheckedKeys(), ...this.$refs.treeRightsRef.getHalfCheckedKeys()]
      // console.log(allkeys)
      // 以逗号分隔的字符串
      const allkeysStr = allkeys.join(',')
      // console.log(allkeysStr)

      // 发起为用户添加权限的请求
      const { data: res } = await commonAPI({ method: 'post', url: `roles/${this.roleId}/rights`, params: { rids: allkeysStr } })
      if (res.meta.status !== 200) return this.$message.error('添加权限失败!')
      this.$message.success('添加权限成功!')

      // 重新请求角色数据
      this.getRoles()
      // 关闭对话框
      this.RightsDialog = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.row_top {
  border-top: 1px solid #eee;
}
.col1_top {
  border-top: none;
}
.row_tag_center {
  display: flex;
  align-items: center;
}
.el-card .el-row {
  margin-bottom: 20px;
}
</style>
